package com.zf.yichat.service.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.mapper.MessageChatroomAdminUserMapper;
import com.zf.yichat.mapper.MessageChatroomMapper;
import com.zf.yichat.model.MessageChatroom;
import com.zf.yichat.model.MessageChatroomAdminUser;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.FsConst;
import io.rong.RongCloud;
import io.rong.methods.chatroom.Chatroom;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.response.ChatroomUserQueryResult;
import io.rong.models.response.ResponseResult;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author wu
 * 群组禁言服务
 */
@Component
public class GroupGagService {

    // 注入配置文件中的融云API配置
    @Value("${rongcloud.key}")
    private String appKey;

    @Value("${rongcloud.secret}")
    private String appSecret;

    @Autowired
    private RongCloudApplication rongCloudApplication;


    public RongCloud rongCloud;

    @Autowired
    private MessageChatroomMapper messageChatroomMapper;

    @Autowired
    private MessageChatroomAdminUserMapper chatroomAdminUserMapper;

    public GroupGagService() {

    }

    // 添加聊天室
    @Transactional
    public Integer createChatroom(String name) throws Exception {
        if (null == rongCloud) {
            rongCloud = RongCloud.getInstance(appKey, appSecret);
        }

        // 创建 Chatroom 实例并设置属性
        Chatroom chatroom = new Chatroom(appKey, appSecret, rongCloud);
        chatroom.setRongCloud(rongCloud);

        // 创建聊天室
        ArrayList<ChatroomModel> modelArrayList = new ArrayList<>();

        ChatroomModel chatroomModel = new ChatroomModel();
        String chatroomId = UUID.randomUUID().toString();
        chatroomModel.setId(chatroomId);  // 聊天室 ID，唯一标识符，最大长度 64 字节。
        chatroomModel.setName(name);  // 聊天室名称，最大长度 128 字节。
        modelArrayList.add(chatroomModel);

        ChatroomModel[] chatroomModels = modelArrayList.toArray(new ChatroomModel[0]);

        // 调用 create 方法创建聊天室
        ResponseResult result = chatroom.create(chatroomModels);
        Integer code = result.getCode();

        if (200 == code) {
            // 保活已创建的聊天室

            HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/keepalive/add");

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("chatroomId", chatroomId));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            // 解析响应数据
            JSONObject jsonObject = JSON.parseObject(response);
            String keepaliveCode = jsonObject.getString("code");
            // 保活聊天室成功后保存聊天室数据到数据库
            if ("200".equals(keepaliveCode)) {
                MessageChatroom messageChatroom = new MessageChatroom();
                messageChatroom.setChatroomId(chatroomId);
                messageChatroom.setChatroomName(name);
                messageChatroom.setCreateTime(new Date());
                messageChatroomMapper.insert(messageChatroom);
            }else {
                return FsConst.Status.EXCEED;
            }

        }
        // 处理 result 中的信息
        return code;
    }


    // 查询所有聊天室
    public List<MessageChatroom> getChatroomList() throws Exception {
        if (null == rongCloud) {
            rongCloud = RongCloud.getInstance(appKey, appSecret);
        }

        // 创建 Chatroom 实例并设置属性
        Chatroom chatroom = new Chatroom(appKey, appSecret, rongCloud);
        chatroom.setRongCloud(rongCloud);

        // 存放存活的聊天室
        List<MessageChatroom> survival = new ArrayList<>();

        // 查询所有创建的聊天室
        List<MessageChatroom> chatroomList = messageChatroomMapper.selectAll();
        for (MessageChatroom messageChatroom : chatroomList) {
            Date createTime = messageChatroom.getCreateTime();
            DateUtils.formatDate(createTime);
            messageChatroom.setCreateTime(createTime);

            // 看一下该聊天室是否存活（如 1 小时内该聊天室中没有发送过新消息或没有用户加入时，则该聊天室将自动销毁）
            String chatroomId = messageChatroom.getChatroomId();

            ChatroomModel chatroomModel = new ChatroomModel();
            chatroomModel.setId(chatroomId);
            chatroomModel.setCount(Integer.MAX_VALUE);
            chatroomModel.setOrder(1);
            ChatroomUserQueryResult queryResult = chatroom.get(chatroomModel);
            if (200 == queryResult.getCode()) {
                survival.add(messageChatroom);
            }
        }
        return survival;
    }

    public boolean chatroomDelete(String chatroomId) throws Exception{

        if (null == rongCloud) {
            rongCloud = RongCloud.getInstance(appKey, appSecret);
        }

        // 创建 Chatroom 实例并设置属性
        Chatroom chatroom = new Chatroom(appKey, appSecret, rongCloud);
        chatroom.setRongCloud(rongCloud);

        // 先查看聊天室是否存在
        ChatroomModel chatroomModel = new ChatroomModel();
        chatroomModel.setId(chatroomId);
        chatroomModel.setCount(Integer.MAX_VALUE);
        chatroomModel.setOrder(1);
        ChatroomUserQueryResult queryResult = chatroom.get(chatroomModel);
        if (200 == queryResult.getCode()) {
            ResponseResult responseResult = chatroom.destroy(chatroomModel);
            if (200 == responseResult.getCode()) {
                // 删除数据库中的数据
                messageChatroomMapper.deleteChatroomByChatroomId(chatroomId);
            }
            return true;
         }
        return false;
    }

    /**
     * 设置聊天室管理员
     * @param chatroomId 聊天室ID
     * @param userIds 管理员ID
     * @return
     * @throws Exception
     */
    public Integer createChatroomAdmin(String chatroomId, String userIds) throws Exception {

        String[] split = userIds.split("\\|");

        HttpPost httpPost = rongCloudApplication.imConstructor("chatroom/user/whitelist/add");

        // 设置请求消息体参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("chatroomId", chatroomId));

        for (int i = 0; i < split.length; i++) {
            params.add(new BasicNameValuePair("userId", split[i]));
        }

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");
        // 管理员设置成功后保存管理员与聊天室的数据到数据库
        if ("200".equals(whitelistCode)) {
            MessageChatroomAdminUser adminUser = new MessageChatroomAdminUser();
            adminUser.setChatroomId(chatroomId);
            for (int i = 0; i < split.length; i++) {
                String userId = split[i];
                adminUser.setUserId(Long.valueOf(userId));
                chatroomAdminUserMapper.insert(adminUser);
            }
            return FsConst.Status.IS_OK;
        }
        return FsConst.Status.EXCEED;
    }
}
